package com.server;

import com.config.Config;
import com.handle.http.NettyHttpHandle;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author linyu.dai
 * @project rpc
 * @description
 * @creat 2022/11/29 19:12:58
 */
@Slf4j
public class HttpServer {

    public static final Integer PORT = Integer.valueOf(Config.get("http.server.port"));

    public static void run() {
        try {
            NioEventLoopGroup group = new NioEventLoopGroup();
            Channel channel = new ServerBootstrap()
                    .group(group)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HttpServerCodec());
                            // 将HTTP消息的多个部分合成一条完整的HTTP消息
                            ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(Integer.MAX_VALUE));
                            //必须在响应转码器下面
                            ch.pipeline().addLast(new NettyHttpHandle());
                            // 响应转码器
                            ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                            // 解决大码流的问题，ChunkedWriteHandler：向客户端发送HTML5文件
                            ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        }
                    }).bind(PORT).sync().channel();
            log.info("httpServer run success:{}",PORT);
            //监听channel关闭
            channel.closeFuture().addListener((future)->{
                group.shutdownGracefully();
            });
        } catch (InterruptedException e) {
            log.error("http server error {}", e.getMessage());
        }
    }
}
